/*
 * @Description: 全宗reducer
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2022-07-04 17:19:41
 */

import {
  ADD_GROUP_PLAN_PROPS,
  SET_EXPANDED_KEYS,
  SET_FLAT_TREE_LIST,
  SET_GROUP_PLAN_LIST,
  SET_SELECTED_KEYS,
  SET_TREE_LIST
} from '../constants';
import { insertItem, selectItemByKey, updateItemById } from '@/utils/list';
import { treeToArr } from '@/utils';

export const FolderTreeReducer = (state, action) => {
  switch (action.type) {
    /**
     * @description: 设置目录树数据
     * @param {Array} data 完整目录树
     * @return {*}
     */
    case SET_TREE_LIST: {
      console.log('SET_TREE_LIST', action.data);
      return {
        ...state,
        treeData: action.data,
        flatTreeList: treeToArr(action.data)
      };
    }

    /**
     * @description: 设置扁平目录树列表
     * @param {Array} data 新增的目录树条目
     */
    case SET_FLAT_TREE_LIST: {
      return {
        ...state,
        flatTreeList: insertItem(action.data, state.flatTreeList)
      };
    }

    /**
     * @description: 设置分组方案列表
     * @param {Array} data 分组方案列表
     */
    case SET_GROUP_PLAN_LIST: {
      return {
        ...state,
        groupTargetList: action.data
      };
    }

    /**
     * @description: 设置目录树展开的key
     * @param {Key[]} data 选中的key
     */
    case SET_EXPANDED_KEYS: {
      return {
        ...state,
        expandedKeys: action.data
      };
    }

    /**
     * @description: 设置目录树选中的key
     * @param {Key[]} data 选中的key
     */
    case SET_SELECTED_KEYS: {
      return {
        ...state,
        selectedKeys: action.data
      };
    }

    /**
     * @description: 设置分组方案列表
     * @param {Array} data 分组方案列表
     */
    case ADD_GROUP_PLAN_PROPS: {
      const { item, propName, data } = action;
      return {
        ...state,
        groupTargetList: updateItemById(
          item.field_name,
          { [propName]: data },
          state.groupTargetList,
          'field_name'
        )
      };
    }

    default:
      console.log('untouched', action);
      return state;
  }
};
